Product of array except self

Time: O(N); Space: O(1); medium

Given an array of n integers where N > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(N).

Example 1:

Input: nums = [1,2,3,4]

Output: [24,12,8,6]

Follow up:

Could you solve it with constant space complexity?

Note:

  • The output array does not count as extra space for the purpose of space complexity analysis.

[1]:
class Solution1(object):
    def productExceptSelf(self, nums):
        """
        :type nums: int[]
        :rtype: int[]
        """
        if not nums:
            return []

        left_product = [1 for _ in range(len(nums))]
        for i in range(1, len(nums)):
            left_product[i] = left_product[i - 1] * nums[i - 1]

        right_product = 1
        for i in range(len(nums) - 2, -1, -1):
            right_product *= nums[i + 1]
            left_product[i] = left_product[i] * right_product

        return left_product
[2]:
s = Solution1()
nums = [1,2,3,4]
assert s.productExceptSelf(nums) == [24,12,8,6]